/* eslint-disable max-lines */
import TauActionPanel from '@/components/TauActionPanel';
import TauPage from '@/components/TauPage';
import TauTable from '@/components/TauTable';
import { useStore } from '@/hooks';
import { Button, Drawer, Message, Dialog } from '@alifd/next';
import { t } from '@lingui/macro';
import { uniqueId } from 'lodash';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useState } from 'react';
import { column, toSelectDataSource, ENUMS } from './stores/definitions';
import { toJS } from 'mobx';
import NoticeForm from './components/NoticeForm';

const tableId = uniqueId('tauTable-');

const Notice = () => {
  const [modal, setModal] = useState({ visible: '', record: {} });
  const { noticeStore: store } = useStore();

  // 获取列表数据
  const handleOnSearch = (params) => {
    const { getOnDate, ...searchArgs } = params.values;
    const [from, to] = getOnDate || [];
    store.search = {
      ...searchArgs,
      from,
      to,
    };
  };

  // 添加公告
  const handleAddNotice = () => {
    setModal({ visible: 'add', record: {} });
  };

  // 查看公告
  const handleViewNotice = (result) => {
    setModal({ visible: 'view', record: result });
  };

  // 编辑公告
  const handleNoticeUpdate = (result) => {
    setModal({ visible: 'edit', record: result });
  };

  // Modal窗口关闭回调
  const handleCancel = () => {
    setModal([]);
  };

  // 删除通知
  const handleRemove = async (result) => {
    Dialog.confirm({
      title: t`确定要删除吗?`,
      onOk: async () => {
        try {
          await store.remove(result?.id);
          Message.success({ content: t`删除成功` });
        } catch (err) {
          Message.error({ content: t`删除失败`, duration: 7000 });
          throw err;
        }
      },
    });
  };

  const handleAnnounceUpdate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        await store.update(toJS(result));
        Message.success({ content: t`公告修政成功` });
      } catch (e) {
        Message.error({ content: t`公告修政失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  const handleAnnounceCreate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        await store.create(toJS(result));
        Message.success({ content: t`公告创建成功` });
      } catch (e) {
        Message.error({ content: t`公告创建失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  const handleCustomRequest = ({ file, onSuccess, onError }) => {
    const reader = new FileReader();
    reader.onloadend = async () => {
      try {
        await RSocket.rc({
          route: 'files.upload',
          args: {
            binary: {
              binaryId: file.uid,
              mimeType: file.type,
              filename: file.name,
            },
          },
          data: Buffer.from(reader.result),
        });
        onSuccess();
      } catch (e) {
        onError(e);
        Message.warning('上传失败');
      } finally {
        // eslint-disable-next-line no-undef
      }
    };
    reader.readAsArrayBuffer(file);
  };

  return (
    <TauPage className="page-container">
      <TauActionPanel
        onSearch={handleOnSearch}
        actions={[].concat(global.isAdmin ? [
          {
            name: 'btn-addNotice',
            title: t`添加公告`,
            type: 'primary',
            onClick: handleAddNotice,
          },
        ] : [])}
        searchItems={[
          {
            name: 'getOnDate',
            type: 'date-range',
            props: {
              placeholder: [t`公告开始时间`, t`公告结束时间`],
            },
          },
          {
            name: 'type',
            type: 'select',
            props: {
              dataSource: toSelectDataSource(ENUMS.type),
              placeholder: t`公告类型`,
            },
          },
          {
            name: 'triggerMethod',
            type: 'select',
            props: {
              dataSource: toSelectDataSource(ENUMS.triggerMethod),
              placeholder: t`触发方式`,
            },
          },
          {
            name: 'interactionMode',
            type: 'select',
            props: {
              dataSource: toSelectDataSource(ENUMS.interactionMode),
              placeholder: t`交互方式`,
              style: { width: '130px' },
            },
          },
        ]}
        keywordSearch={{
          placeholder: t`请输入关键字搜索`,
        }}
        className="action-panel"
      />
      <div className="content">
        <TauTable
          instanceId={tableId}
          primaryKey="id"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={store.total}
          onFetch={(pg) => {
            store.pg = pg;
          }}
          loading={store.loading}
          dataSource={toJS(store.data)}
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            column('id', {
              width: 200,
              cell: (v, __, r) => (
                <Button type="primary" text onClick={() => handleViewNotice(r)}>
                  {v}
                </Button>
              ),
            }),
            column('name', {}),
            column('mainTitle', {}),
            column('type', {}),
            column('triggerMethod', {}),
            column('interactionMode', {}),
            column('sortWeight', {}),
            column('content', {}),
            column('enable', {}),
            {
              title: t`操作`,
              dataIndex: 'Number',
              width: 180,
              cell: (_, i, notify) => (
                <>
                  <Button text type="primary" onClick={() => handleNoticeUpdate(notify)}>{t`编辑`}</Button>
                  <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
                  <Button text type="primary" style={{ color: 'red' }} onClick={() => handleRemove(notify)}>{t`删除`}</Button>
                </>
              ),
            },
          ]}
        />
      </div>
      <Drawer
        visible={modal.visible === 'add' || modal.visible === 'view' || modal.visible === 'edit'}
        title={modal.visible === 'add' ? t`添加公告` : t`编辑公告`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal({ close: `toClose$${Date.now()}` })}
        width="100%"
      >
        <NoticeForm
          noticeInfo={modal.record}
          modal={modal.visible}
          onCancel={handleCancel}
          handleCustomRequest={handleCustomRequest}
          onSubmit={modal.visible === 'add' ? handleAnnounceCreate : handleAnnounceUpdate}
        />
      </Drawer>
    </TauPage>
  );
};

export default observer(Notice);
